
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
const cors = require('cors') 
const {verifyToken} = require('./utils/config.js')


//引入首页路由
var indexRouter = require('./routes/index');
//引入列表路由
var listRouter = require('./routes/list');
//引入课程路由
var courseRouter = require('./routes/course');
//引入登录注册
var loginRouter = require('./routes/login');

var personRouter = require('./routes/person');


var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(cors())
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/uploads',express.static(path.join(__dirname, 'uploads')));

//使用路由
// 首页
app.use('/api', indexRouter);
// 列表
app.use('/api', listRouter);
// 课程
app.use('/api', courseRouter);
//登录注册
app.use('/api', loginRouter);
//personRouter


app.use(function (req, res, next) {
  let token = req.headers.authorization
  // let token = localStorage.getItem('token')
  if (!verifyToken(token)) {
    next({
      msg: '请传递token',
      status: 500
    })

    return
  }
  next()
})
app.use('/api', personRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  // next(createError(404));
  res.send('404错误')
});

// error handler
app.use(function(err, req, res, next) {
  res.send(err)
});

module.exports = app;
